using System.Collections;
using System.Collections.Generic;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using UnityEngine;
using UnityEngine.EventSystems;


public class DragBag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    Vector3 original_position;
    Vector3 begin_position;
    Vector3 end_position;

    BdTools.GameInfo game_info_obj
    {
        get
        {
            return BdTools.FileTools.instance.game_info_obj;
        }
    }

    public void set_ui_bag_position(Vector3 ui_bag_position)
    {
        float x = BdUtils.round(ui_bag_position.x / Screen.width, 3);
        float y = BdUtils.round(ui_bag_position.y / Screen.height, 3);

        var _ui_bag_position = BdUtils.conv_obj_to_list<float>(new float[] { x, y });
        BdUtils.log("--- on set position, _ui_bag_position:", _ui_bag_position);

        file_obj.content_dc[key] = _ui_bag_position;
        file_obj.save();
    }
    
    private string file_name => $"ui/bag/{gameObject.name}";

    private string key = "ui_bag_position";
    AppFileTools.FileObject file_obj;

    private void Start()
    {
        file_obj = new AppFileTools.FileObject(file_name: file_name, create_if_not_exists: true);
        
        var ui_bag_position = file_obj.content_dc.TryGetValue(key, out var _value) ? BdUtils.conv_obj_to_list<float>(_value) : null;
        
        if (ui_bag_position != null)
        {
            transform.position = new Vector3(ui_bag_position[0] * Screen.width, ui_bag_position[1] * Screen.height);
            adjust_position_by_screen_size();
        }
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        begin_position = eventData.position;
    }

    public void OnDrag(PointerEventData eventData)
    {
        end_position = eventData.position;
        move_to_end_position();
    }

    void adjust_position_by_screen_size()
    {
        float x = Mathf.Clamp(transform.position.x, 0.2f * Screen.width, 0.8f * Screen.width);
        float y = Mathf.Clamp(transform.position.y, 0.4f * Screen.height, 0.6f * Screen.height);
        transform.position = new Vector2(x, y);
    }

    public void move_to_end_position()
    {
        var delta = end_position - begin_position;
        if (delta.magnitude > 1f)
        {
            transform.position += delta;
            adjust_position_by_screen_size();

            begin_position = end_position;
        }
    }

    void IEndDragHandler.OnEndDrag(PointerEventData eventData)
    {
        end_position = eventData.position;

        move_to_end_position();
        set_ui_bag_position(transform.position);
    }
}